package com.cincc.taofangwang.widget;

import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.cincc.taofangwang.R;
import com.cincc.taofangwang.adapter.TaskNameAdapter;
import com.cincc.taofangwang.common.MyUtils;
import com.cincc.taofangwang.common.OkHttpUtils;
import com.cincc.taofangwang.common.callback.OnClickCallBack;
import com.cincc.taofangwang.common.callback.TaskCallBack;
import com.cincc.taofangwang.constant.CallConstant;
import com.cincc.taofangwang.model.TaskModel;
import com.lxj.xpopup.core.DrawerPopupView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;

public class CustomDrawerPopupView extends DrawerPopupView {
    private static final String TAG = "CustomDrawerPopupView";
    Activity context;
    int statusBarHeight = 0;
    TaskCallBack onClickCallBack;

    public CustomDrawerPopupView(@NonNull Context context, int statusBarHeight, TaskCallBack onClickCallBack) {
        super(context);
        this.context = (Activity) context;
        this.statusBarHeight = statusBarHeight;
        this.onClickCallBack = onClickCallBack;
    }

    @Override
    protected int getImplLayoutId() {
        return R.layout.custom_drawer_popup;
    }

    RecyclerView recyclerView;
    TaskNameAdapter adapter;
    SmartRefreshLayout refreshLayout;

    //每次加载数量
    int limit = 100;
    //加载位置
    int start = 0;

    @Override
    protected void initPopupContent() {
        super.initPopupContent();
        recyclerView = findViewById(R.id.recycler_task_name);
        LinearLayout layout = findViewById(R.id.drawer_ll);
        FrameLayout.LayoutParams layoutParams = (LayoutParams) layout.getLayoutParams();
        layoutParams.width = (int) Math.round(MyUtils.getWidth(context) * 0.7);
        refreshLayout = findViewById(R.id.refreshLayout);
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            start = 0;
            list.clear();
            getTaskAndService();
        });
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            getTaskAndService();
        });
        TextView title = findViewById(R.id.user_text);
        RelativeLayout titleRelayout = findViewById(R.id.title_relayout);
        title.setText(CallConstant.NAME);
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) titleRelayout.getLayoutParams();
        lp.topMargin = statusBarHeight + 20;
        adapter = new TaskNameAdapter(context, list);
        adapter.setCallBack(taskId -> {
            onClickCallBack.callback(taskId);
            dismiss();
        });
        recyclerView.setAdapter(adapter);
        getTaskAndService();
    }

    List<TaskModel> list = new ArrayList<>();

    private void refreshUI(JSONArray array) {
        try {
            for (int i = 0; i < array.length(); i++) {
                TaskModel model = new TaskModel(array.getJSONObject(i).getString("p_task_id"), array.getJSONObject(i).getString("p_task_name"));
                list.add(model);
            }
            start = list.size();
            adapter.notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getTaskAndService() {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", "Agent");
            jsonObject.put("limit", limit);
            jsonObject.put("start", start);
            jsonObject.put("act", "getTaskAndService");
            jsonObject.put("time", MyUtils.getCurrentTime());
            jsonObject.put("token", CallConstant.TOKEN);
            doRequest(jsonObject.toString());
        } catch (Exception e) {
            Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void doRequest(String data) {
        Log.e(TAG, "doRequest: " + data);
        OkHttpUtils.httpPost(CallConstant.REQUEST_PATH, data, new HashMap<>(), new OkHttpUtils.ICallBack() {
            @Override
            public void onSuccessful(Call call, String data) {
                Log.e(TAG, "onSuccessful: " + data);
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    int code = jsonObject.getInt("response_code");
                    String msg = jsonObject.getString("response_msg");
                    if (code == 0) {
                        JSONArray data1 = jsonObject.getJSONArray("data");
                        context.runOnUiThread(() -> refreshUI(data1));
                    } else {
                        context.runOnUiThread(() -> Toast.makeText(context, msg, Toast.LENGTH_SHORT).show());
                    }
                } catch (JSONException e) {
                    context.runOnUiThread(() -> Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show());
                } finally {
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore();
                }
            }

            @Override
            public void onFailure(Call call, String errorMsg) {
                Log.e(TAG, "onFailure: " + errorMsg);
                context.runOnUiThread(() -> Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show());
            }
        });
    }
}
